/**
 * 
 */
package com.therandoms.rtgdroid.background;

import java.io.File;
import java.io.FileOutputStream;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.therandoms.textgen.MusicGenerator;

import android.content.Intent;
import android.net.Uri;
import jm.util.Write;
import android.os.AsyncTask;
import android.os.Environment;

/**
 * A simple AsyncTask that produces a {@link URI} for passing Android media
 * through an {@link Intent#ACTION_SEND}
 * 
 * @author logan
 * @param <T>
 */
public class MusicGeneratorAsyncTask<T> extends AsyncTask<T, Integer, Uri> {

	/**
	 * The output directory to use for music.
	 */
	public static final String GENERATED_MUSIC_OUTPUT_DIRECTORY = "RandomTextGen"
			+ File.separator + "OutputMusic";

	@Override
	protected Uri doInBackground(T... params) {
		//create the required directories
		File extStorageDir = Environment.getExternalStorageDirectory();
		File outDir = new File(extStorageDir.getAbsolutePath() + File.separator
				+ GENERATED_MUSIC_OUTPUT_DIRECTORY);
		if (!outDir.mkdirs() && !outDir.isDirectory()) {
			return null;
		}
		
		//get the name of the file
		SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.getDefault());
		String mDate = fmt.format(new Date());
		File mFile = new File(outDir.getAbsolutePath() + File.separator + mDate + ".midi");

		//make the file
		try {
			FileOutputStream fos = new FileOutputStream(mFile);
			Write.midi(MusicGenerator.makeScoreFromBytes(params[0]), fos);
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
		//get the URI for an android action_send intent. 
		return Uri.fromFile(mFile);
	}

}
